<?php
/**
 * User: Tony Chen
 * Date: 2017/7/23.
 */

class Mysql
{
    private $mysqli = null;

    public function __construct($host, $user, $password, $dbName)
    {
        $this->mysqli = new mysqli($host, $user, $password, $dbName);

        if ($this->mysqli->connect_errno) {
            exit("Failed to connect to MySQL: (" . $this->mysqli->connect_errno . ") " . $this->mysqli->connect_error);
        }
    }

    /**
     * 插入数据
     * @param $sql
     * @return bool|mysqli_result
     */
    public function insert($sql)
    {
        return $this->mysqli->query($sql);
    }

    /**
     * 插入数据
     * @example $mysqli->insert('user', ['username' => $post['username'], 'password' => md5($post['password']), 'create_time' => date('Y-m-d H:i:s')]);
     * @param string $table 表名
     * @param array $content 数据数组  ['filed'=>'value','filed'=>'value'] 数组形式
     *
     * @return bool
     */
    public function add($table, $content)
    {
        $filed = array_keys($content);
        $value = array_values($content);

        $sqlField = implode(',', $filed);

        $sqlValue = '(';
        foreach ($value as $val) {
            $sqlValue .= "'" . $val . "', ";
        }

        $sqlValue = rtrim($sqlValue, ', ') . ')';

        // $sql = "INSERT INTO user (username, password, create_time) VALUE ('admin', 'aaaa', '2017-07-22 00:00:00')";
        $sql = "INSERT INTO {$table} ({$sqlField}) VALUE {$sqlValue}";

        return $this->mysqli->query($sql);
    }

    public function select($sql)
    {
        // SELECT password FROM user WHERE username = 'admin';
        $ret = $this->mysqli->query($sql);

        if ($ret->num_rows === 0) {
            return false;
        }

        return $ret->fetch_all(MYSQLI_ASSOC);
    }

    public function delete()
    {
    }

    public function update()
    {

    }


    public function __destruct()
    {
        echo '<br>';
        echo $this->mysqli->error;
        $this->mysqli->close();
    }

}